// packageStore/pages/purchase/chooseProductGift/chooseProductGift.js
const app = getApp()
const componentBehavior = require('../../../../js/common/ComponentBehavior')

import { calculation } from '../../../../js/common/math'
import {
  alert,
  deepClone,
  isEmpty
} from '../../../../js/newUtil'
import {
  api,
  util,
} from '../../../../js/util'

Page({
  behaviors: [componentBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    imgDomain: api.imgDomain,
    enableOss: api.enableOss,
    mainColor: api.titleColor || "#e56b14", //主题色
    Currency:api.Currency || '￥',//货币符号
    selectedGift: {}, // 已选赠品信息
    priceDigits: 2,
    key0: '', // id_规则id_商品id
    key1: '', // id_规则id_商品id_当前阶梯index
    list: [], // 赠品列表
    good: {}, // 当前商品信息
    rule: {}, // 规则信息
    count: 0, // 可选数量
    Promotion: {}, // 促销信息
    loaded: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    wx.setNavigationBarColor({
      backgroundColor: api.titleColor || "#e56b14", //主题色,
      frontColor: '#ffffff',
    })
    this.setData({
      mainColor: api.titleColor || "#e56b14"
    })
    this.getPrevPageData()
  },
  /**
   * 获取上个页面的数据
   */
  getPrevPageData() {
    let pages = getCurrentPages()
    let prevPage = pages[pages.length - 2]
    let cartlist = prevPage.data.cartlist || []
    let priceDigits = prevPage.data.priceDigits || 2
    let chooseGiftIndex = prevPage.data.chooseGiftIndex || []
    let rule = {}
    let good = {}
    let Id = ''
    let RuleId = ''
    let GoodsId = ''
    let info = {}
    let Promotion = {}
    let PromotionType = 1 // 促销类型 1单品 2组合
    let currentLadder = {} // 当前满足的促销阶梯规则
    let list = [] // 赠品列表
    let count = 0 // 可选赠品最大值
    let value = [] // 当前选中的index列表
    let promotionIndex = -1
    let key0 = ''
    let key1 = ''
    if (chooseGiftIndex.length == 2) { // 组合促销
      try {
        rule = cartlist[chooseGiftIndex[0]].PromotRules[chooseGiftIndex[1]]
      } catch (err) {
        console.log(err)
      }
      if (isEmpty(rule)) {
        alert({
          content: '解析促销信息失败',
          success() {
            wx.navigateBack()
          }
        })
        return
      }
      Id = cartlist[chooseGiftIndex[0]].Id
      RuleId = rule.RuleId
      GoodsId = ''
      info = rule.info || {}
      Promotion = rule.Promotion || {}
      PromotionType = Promotion.PromotionType || 1 // 促销类型 1单品 2组合
      currentLadder = info.currentLadder || {} // 当前满足的促销阶梯规则
      list = currentLadder.GiftsList // 赠品列表
      count = currentLadder.GiveCount || list.length // 可选赠品最大值
      value = [] // 当前选中的index列表
      promotionIndex = info.promotionIndex
      key0 = `${Id}_${RuleId}_0`
      key1 = `${Id}_${RuleId}_0_${promotionIndex}`
    } else { // 单品促销
      try {
        good = cartlist[chooseGiftIndex[0]].PromotRules[chooseGiftIndex[1]].Products[chooseGiftIndex[2]].Goods[chooseGiftIndex[3]] || {}
      } catch (err) {
        console.log(err)
      }
      if (isEmpty(good)) {
        alert({
          content: '解析促销信息失败',
          success() {
            wx.navigateBack()
          }
        })
        return
      }
      Id = good.Id
      RuleId = good.RuleId
      GoodsId = good.GoodsId
      info = good.info || {}
      Promotion = good.Promotion || {}
      PromotionType = Promotion.PromotionType || 1 // 促销类型 1单品 2组合
      currentLadder = info.currentLadder || {} // 当前满足的促销阶梯规则
      list = currentLadder.GiftsList || [] // 赠品列表
      count = currentLadder.GiveCount || list.length // 可选赠品最大值
      value = [] // 当前选中的index列表
      promotionIndex = info.promotionIndex
      key0 = `${Id}_${RuleId}_${GoodsId}`
      key1 = `${Id}_${RuleId}_${GoodsId}_${promotionIndex}`
    }
    let selectedGift = prevPage.data.selectedGift || {} // 上个页面的已选的赠品信息
    if (!isEmpty(selectedGift[key0]) && selectedGift[key0].key == key1) {
      value = selectedGift[key0].indexValue
    } else { // 没有选时，默认前n个被选中
      for (let i = 0; i < count; i++) {
        value.push(i)
      }
      if (isEmpty(selectedGift[key0])) {
        selectedGift[key0] = {}
      }
    }
    let ids = []
    for (let i = 0; i < list.length; i++) {
      if (value.includes(i)) {
        list[i].selected = true
        ids.push(list[i].Id)
      }
      let item = list[i]
      let showPrice = 0
      let showStock = 0
      showPrice = item.Price || 0
      if (item.IsUseRealStock == 1) {
        showStock = item.Stock
      } else {
        showStock = item.GiftStock
      }
      item.GiftTranslated = parseFloat(item.GiftTranslated || 1)
      // 当非基础单位时，库存和价格需要进行换算
      if (item.GiftTranslated != 1) {
        showPrice = parseFloat(showPrice)
        showStock = parseFloat(showStock)
        showStock = calculation(showStock, '/', item.GiftTranslated)
      }
      list[i].showStock = showStock
      list[i].showPrice = showPrice
    }
    if (ids.length == 0) {
      ids = -1
    } else {
      ids = ids.join(',')
    }
    let selectedInfo = ''
    if (PromotionType == 1) {
      selectedInfo = `<goods_${GoodsId}>${ids}</goods_${GoodsId}>`
    } else {
      selectedInfo = `<promot_${RuleId}>${ids}</promot_${RuleId}>`
    }
    selectedGift[key0].indexValue = value
    selectedGift[key0].key = key1
    selectedGift[key0].selectedInfo = selectedInfo
    this.setData({
      selectedGift,
      list,
      good,
      rule,
      count,
      key0: key0,
      key1: key1,
      Promotion,
      priceDigits,
      loaded: true
    })
  },

  select(e) {
    let index = e.currentTarget.dataset.index
    let {
      list,
      count
    } = this.data
    list = deepClone(list)
    if (list[index].selected) {
      list[index].selected = false
    } else {
      list[index].selected = true
    }
    let selectedList = list.filter((item) => {
      return item.selected
    })
    if (selectedList.length > count) {
      alert(`已达到所选赠品种数，不能继续选择！`)
      return
    }
    this.setData({
      list
    })
  },

  confirm() {
    let {
      list,
      good,
      rule,
      selectedGift,
      key0,
      Promotion
    } = this.data
    let RuleId = ''
    let GoodsId = ''
    let PromotionType = Promotion.PromotionType || 1 // 促销类型 1单品 2组合
    if (PromotionType == 2) {
      RuleId = rule.RuleId
      GoodsId = ''
    } else {
      RuleId = good.RuleId
      GoodsId = good.GoodsId
    }
    let value = []
    let ids = []
    list.map((item, index) => {
      if (item.selected) {
        value.push(index)
        ids.push(item.Id)
      }
    })
    if (ids.length == 0) {
      ids = -1
    } else {
      ids = ids.join(',')
    }
    let selectedInfo = ''
    if (PromotionType == 1) {
      selectedInfo = `<goods_${GoodsId}>${ids}</goods_${GoodsId}>`
    } else {
      selectedInfo = `<promot_${RuleId}>${ids}</promot_${RuleId}>`
    }
    selectedGift[key0].indexValue = value
    selectedGift[key0].selectedInfo = selectedInfo
    let pages = getCurrentPages()
    let prevPage = pages[pages.length - 2]
    prevPage.setData({
      selectedGift
    })
    wx.navigateBack()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
})